package ink.xiaobaibai.controller.coupon;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ink.xiaobaibai.common.CouponStatus;
import ink.xiaobaibai.common.MySecurity;
import ink.xiaobaibai.common.ServiceResult;
import ink.xiaobaibai.entity.Coupon;
import ink.xiaobaibai.entity.CouponUser;
import ink.xiaobaibai.multipleClick.ForbidMultipleClick;
import ink.xiaobaibai.response.ResponseFormat;
import ink.xiaobaibai.service.ICouponService;
import ink.xiaobaibai.service.ICouponUserService;
import ink.xiaobaibai.vo.CouponVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 优惠券接口
 * @author: 小白白
 * @create: 2021-06-05
 **/

@Api(tags = "查看自己的优惠券(仅单次支付用)")
@RequestMapping("/coupon")
@RestController
public class CouponController {

    @Autowired
    private ICouponService couponService;

    @Autowired
    private ICouponUserService couponUserService;

    @GetMapping("/can-use-list")
    @ApiOperation("查看自己的可用优惠券集合")
    public ResponseFormat list() {
        Integer userId = MySecurity.getUserId();
        QueryWrapper<CouponUser> q1 = new QueryWrapper<>();
        q1.select("coupon_id", "expires_time");
        q1.eq("user_id", userId);
        q1.in("status", CouponStatus.CAN_USE.getStatus());
        List<CouponUser> list = this.couponUserService.list(q1);
        long time = System.currentTimeMillis();
        List<Integer> ids = list.stream().filter(l -> l.getExpiresTime().getTime() > time).map(CouponUser::getCouponId).collect(Collectors.toList());
        if (ids.size() == 0) {
            return ResponseFormat.success();
        }
        QueryWrapper<Coupon> q2 = new QueryWrapper<>();
        q2.select("id", "name", "percentage", "type");
        q2.in("id", ids);
        q2.eq("stop_use", false);
        List<CouponVo> resultList = this.couponService.list(q2).stream().map(c -> new CouponVo(c.getId(), c.getName(), this.getExpireTimeByCouponUserList(c.getId(), list), c.getPercentage(), c.getType())).collect(Collectors.toList());
        return ResponseFormat.success(resultList);
    }

    /**
     * 查看可领取的优惠券
     */
    @GetMapping("/can-receive-list")
    @ApiOperation("查看当前用户可领取的优惠券")
    public ResponseFormat canReceiveList() {
        List<Coupon> canReceiveCouponByUserId = this.couponService.getCanReceiveCouponByUserId(MySecurity.getUserId());
        List<Coupon> list = canReceiveCouponByUserId.stream().filter(c -> c.getRemainingCount() > 0).collect(Collectors.toList());
        return ResponseFormat.success(list);
    }

    /**
     * 领取当前优惠券
     */
    @GetMapping("/receive/{id}")
    @ApiOperation("领取当前优惠券")
    @ForbidMultipleClick(key = "#couponId", msg = "领取人数过多,请5秒后再试", durationSecondsTime = 3)
    public ResponseFormat receiveCoupon(@PathVariable("id") Integer couponId) {
        ServiceResult serviceResult = this.couponService.receiveThisCouponById(couponId, MySecurity.getUserId());
        if (!serviceResult.isOk()) {
            return ResponseFormat.fail(serviceResult.getMsg());
        }
        return ResponseFormat.success();
    }

    private Date getExpireTimeByCouponUserList(Integer couponId, List<CouponUser> list) {
        for (CouponUser couponUser : list) {
            if (couponUser.getCouponId().equals(couponId)) {
                return couponUser.getExpiresTime();
            }
        }
        return null;
    }

}
